from django.shortcuts import render
from django.template import RequestContext, loader
from django.http import HttpResponse, JsonResponse
from datetime import datetime
import time
from geopy.distance import geodesic
from django.shortcuts import redirect
from xyss_admin.models import SchoolLocation, Students,CourseMaster,CourseSlave


# Create your views here.
def scan(request):
    template = loader.get_template('scan/index.html')
    return HttpResponse(template.render())


def redirect_scan(request):
    template = loader.get_template('scan/redirect_scan.html')
    return HttpResponse(template.render())


def qrcocde(request):
    template = loader.get_template('scan/qrcode.html')
    return HttpResponse(template.render())


def check_assign(request):
    name = request.GET['name'].strip("'")
    class_name = request.GET['class_name'].strip("'")
    course_name = request.GET['course_name'].strip("'")
    # 这是用户坐标
    lat = request.GET['lat']
    long = request.GET['long']
    # 学校的坐标后期要在管理后台管理起来  这里需要用到地图
    school_station = SchoolLocation.objects.all().last()
    school_station = (school_station.lat, school_station.long)
    distance = calculate_distance(school_station, (lat, long))

    # 生成一个时间戳  调用接口的时候，
    current_time = datetime.now()
    current_time = current_time.replace(microsecond=0)
    timestamp = change_date(str(current_time))

    # 学生信息，学生专业信息，专业的课程表信息 在后台都要管理起来
    # 第一步先查学生，条件是不是就传递过来的学生姓名
    stu_info = Students.objects.get(username=name)
    if stu_info is None:
        # 查不到人
        return redirect('/scan/success?code=2')

    # 有这个学生，第二部判断，专业是否对的上
    _class = ""
    if stu_info.class_name == 1:
        _class = '24电商综合一班'
    elif stu_info.class_name == 2:
        _class = '22大数据软件开发'
    elif stu_info.class_name == 3:
        _class = '23网络技术'
    elif stu_info.class_name == 4:
        _class = '21幼师'

    if _class == "" or _class != class_name:
        print('专业为空或者专业名字没匹配')
        return redirect('/scan/success?code=7')

    # 第三部查找专业课程，看是否对的上,好的习惯，就是学会判空
    course_id = stu_info.course_id_id
    master_obj = CourseMaster.objects.get(id=course_id)
    if master_obj is None:
        print('后台没有设置课程，请通知管理员设置课程')
        return redirect('/scan/success?code=4')

    # 之后要修改，不要course_ids字段
    id_list = master_obj.course_ids.split(',')
    course_obj = CourseSlave.objects.filter(id__in=id_list)
    if course_obj is None:
        print('课程没有详细安排')
        return redirect('/scan/success?code=5')

    # 根据当前时间，去匹配课程表中课程的时间和信息
    _now = datetime.now()
    hour_minute = _now.strftime('%H:%M')
    weekday = _now.weekday()
    weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    weekday_cn = weekdays[weekday]
    # 循环课程表，匹配当前接口传递过来的课程，1）如果匹配的上，继续匹配时间 2）匹配不上，直接返回错误

    today_courses = []
    for temp in course_obj:
        if temp.name == weekday_cn:
            today_courses.append(temp.first_class)
            today_courses.append(temp.second_class)
            today_courses.append(temp.third_class)
            today_courses.append(temp.fourth_class)
            today_courses.append(temp.fifth_class)
            today_courses.append(temp.sixth_class)

    if today_courses == "":
        print('当天没有课程安排')
        return redirect('/scan/success?code=8')

    current_date = _now.strftime("%Y-%m-%d")
    # 每天课程 8:40 9:30 10:30 11:20 14:40 15:30
    first_class_time = current_date + ' 8:40:00'
    _first_class_time = current_date + ' 8:30:00'
    first_stamp = dateStrTotimeStamp(first_class_time)
    _first_stamp = dateStrTotimeStamp(_first_class_time)

    second_class_time = current_date + ' 9:30:00'
    _second_class_time = current_date + ' 9:20:00'
    second_stamp = dateStrTotimeStamp(second_class_time)
    _second_stamp = dateStrTotimeStamp(_second_class_time)

    third_class_time = current_date + ' 10:30:00'
    _third_class_time = current_date + ' 10:20:00'
    third_stamp = dateStrTotimeStamp(third_class_time)
    _third_stamp = dateStrTotimeStamp(_third_class_time)

    fourth_class_time = current_date + ' 11:20:00'
    _fourth_class_time = current_date + ' 11:10:00'
    fourth_stamp = dateStrTotimeStamp(fourth_class_time)
    _fourth_stamp = dateStrTotimeStamp(_fourth_class_time)

    fifth_class_time = current_date + ' 14:40:00'
    _fifth_class_time = current_date + ' 14:30:00'
    fifth_stamp = dateStrTotimeStamp(fifth_class_time)
    _fifth_stamp = dateStrTotimeStamp(_fifth_class_time)

    sixth_class_time = current_date + ' 15:30:00'
    _sixth_class_time = current_date + ' 15:20:00'
    sixth_stamp = dateStrTotimeStamp(sixth_class_time)
    _sixth_stamp = dateStrTotimeStamp(_sixth_class_time)

    n = ''
    if _first_stamp < timestamp < first_stamp:
        n = 1
        print('打卡第一节课')
    elif _second_stamp < timestamp < second_stamp:
        print('打卡第二节课')
        n = 2
    elif _third_stamp < timestamp < third_stamp:
        print('打卡第三节课')
        n = 3
    elif _fourth_stamp < timestamp < fourth_stamp:
        print('打卡第四节课')
        n = 4
    elif _fifth_stamp < timestamp < fifth_stamp:
        print('打卡第五节课')
        n = 5
    elif _sixth_stamp < timestamp < sixth_stamp:
        print('打卡第六节课')
        n = 6
    else:
        print('没有在指定时间段内打卡')
        return redirect('/scan/success?code=6')

    course_res = ''
    try:
        course_res = today_courses[n-1]
    except Exception as e:
        print('log ..... 课程没有取的上')

    if course_res == '' or course_res != course_name:
        return redirect('/scan/success?code=2')

    return redirect('/scan/success?code=1')


def change_date(time_str):
    """
    将%Y-%m-%d %H:%M:%S日期转换成时间戳
    :param time_str:
    :return:
    """
    dt_obj = datetime.strptime(str(time_str), "%Y-%m-%d %H:%M:%S")
    # 将datetime对象转换为时间戳
    timestamp = int(time.mktime(dt_obj.timetuple()))
    return timestamp


def calculate_distance(coord1, coord2):
    """
    计算两个经纬度坐标之间的距离

    :param coord1: 第一个坐标，格式为 (纬度, 经度)
    :param coord2: 第二个坐标，格式为 (纬度, 经度)
    :return: 距离（单位：千米）
    """
    distance = geodesic(coord1, coord2).kilometers
    return distance


def success(request):
    code = int(request.GET['code'])
    msg = '签到成功'
    if code == 1:
        msg = '签到成功'
    elif code == 2:
        msg = '学生不存在，打卡失败'
    elif code == 3:
        msg = '没有抵达教室，打卡失败'
    elif code == 4:
        msg = '后台没有设置课程，请通知管理员设置课程，打卡失败'
    elif code == 5:
        msg = '课程没有详细安排，打卡失败'
    elif code == 6:
        msg = '没有在指定时间内打卡，打卡失败'
    elif code == 7:
        msg = '专业为空或者专业名字没匹配，打卡失败'
    elif code == 8:
        msg = '当天没有课程安排，打卡失败'
    elif code == 9:
        msg = '签到课程错误，打卡失败'

    data = {'msg': msg, 'code': code}
    return render(request, 'scan/success.html', data)


def dateStrTotimeStamp(_now):
    date_str = _now # 格式为年-月-日
    # 将字符串转换为datetime对象
    dt_object = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    # 将datetime对象转换为时间戳
    timestamp = int(time.mktime(dt_object.timetuple()))
    return timestamp